package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by admin on 2019/8/8.
 */

/**
 * 用户参数解析器
 * <p>
 * 实现的功能:
 * 将当前登陆的用户对象，以形式参数的格式注入到请求映射方法中
 */

public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IUserInfoRedisService redisService;

    //明确要注入对象的类型
    //如果为true，表示支持该类型，如果为false，表示不支持
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {

        //methodParameter.getParameterType()表示映射方法参数类型
        return methodParameter.getParameterType() == UserInfo.class
                && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    //UserInfo userInfo形式参数注入逻辑
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory)
            throws Exception {
        //获取当前的请求对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getCookie(request);
        UserInfo userInfo = redisService.getUserInfoToken(token);
        return userInfo;
    }
}
